<?php
/**
 * Service class for search module
 *
 * @author Ishtiaque Shahrier <md.ishtiaque@newgenbd.net>
 * @package search
 * @subpackage libraries
 */
class service_l_search {

    public function __construct() {

    }
    /**
     * Query the db and return params if any
     * 
     * @param string type of param (see the module_u_search type constants)
     * @return mixed array of param_m_search or NULL
     */
    public function get_params($type=NULL) {
        $obj = new param_m_search();
        if ($type !== NULL) {
            $obj->where("type", $type);
        }
        $params = $obj->get_iterated();
        return $params->result_count() > 0 ? $params : NULL;
    }

    public function get_param_object($id) {
        return get_object($id, "param_m_search");
    }

    /**
     * Analyse the URL and detects the param pattern from URL.
     * A param is supplied in the url generally like this -  p?[id]:[option(if any)]
     * This method do not add the detected param in your search sql but just tells
     * you that these are the possible/detected search/sort params.thats it!
     * 
     * @return array array of param_m_search 
     */
    public function grab_url_params() {
        $segments = get_instance()->uri->segment_array();
        $param_objs = array();
        foreach ($segments as $segment) {
            //@TO_DO : use regular expression instead of startwith(..)
            if (starts_with($segment, module_u_search::SEARCH_PARAM_STARTS_WITH)) {
                $tmp = explode(module_u_search::SEARCH_PARAM_DIVIDER, $segment); //p?1:asc - break this
                $tmp2 = explode(module_u_search::SEARCH_PARAM_ID_VAL_SEPERATOR, $tmp[1]); //1:asc - now break this                
                if (count($tmp) == 2 && count($tmp2) > 1) {
                    $id = $tmp2[0];
                    if(is_numeric($id)){
                        $param_db_object = $this->get_param_object($id);
                        if ($param_db_object) {
                            //lets deal with a simple set of data instead of DMZ
                            $param_db_object = $param_db_object->convert_to_simple_data();
                            //get option from p?id:option or use db defalt option
                            $param_db_object->option = isset($tmp2[1]) ? $tmp2[1] : xss_clean($param_db_object->option);
                            $param_objs[] = $param_db_object;
                        } else {
                            logger::i()->error("Search driver not found in DB with id: $id ", "driver", "search");
                        }
                    }
                }
            }
        }
        
        return $param_objs;
    }

}

?>